import 'package:flutter_test/flutter_test.dart';
import 'package:ghpfc_fmp/core/database_helper.dart';
import 'package:ghpfc_fmp/services/user_service.dart';
import 'package:ghpfc_fmp/models/user.dart';

void main() {
  group('用户管理功能测试', () {
    late UserService userService;

    setUpAll(() async {
      // 初始化数据库
      await DatabaseHelper.initializeDatabaseFactory();
      final dbHelper = DatabaseHelper();
      await dbHelper.database;
      userService = UserService();
    });

    group('用户CRUD操作测试', () {
      test('创建用户测试', () async {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        final user = User(
          username: 'testuser_$timestamp',
          passwordHash: DatabaseHelper.hashPassword('testpass123'),
          realName: '测试用户',
          email: 'test@example.com',
          phone: '13800138000',
          role: 1,
          department: '技术部',
          position: '开发工程师',
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final success = await userService.createUser(user);
        expect(success, isTrue);

        // 验证用户是否创建成功
        final createdUser = await userService.getUserByUsername('testuser_$timestamp');
        expect(createdUser, isNotNull);
        expect(createdUser!.username, equals('testuser_$timestamp'));
        expect(createdUser.realName, equals('测试用户'));
        expect(createdUser.role, equals(1));
      });

      test('更新用户测试', () async {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        // 先创建用户
        final user = User(
          username: 'updateuser_$timestamp',
          passwordHash: DatabaseHelper.hashPassword('testpass123'),
          realName: '更新测试用户',
          email: 'update@example.com',
          phone: '13800138000',
          role: 1,
          department: '技术部',
          position: '开发工程师',
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final createSuccess = await userService.createUser(user);
        expect(createSuccess, isTrue);

        // 获取用户
        final createdUser = await userService.getUserByUsername('updateuser_$timestamp');
        expect(createdUser, isNotNull);

        // 更新用户信息
        final updatedUser = createdUser!.copyWith(
          realName: '更新后的测试用户',
          email: 'updated@example.com',
          department: '产品部',
          updatedAt: DateTime.now(),
        );

        final success = await userService.updateUser(updatedUser);
        expect(success, isTrue);

        // 验证更新是否成功
        final updatedUserFromDb = await userService.getUserById(createdUser.id!);
        expect(updatedUserFromDb, isNotNull);
        expect(updatedUserFromDb!.realName, equals('更新后的测试用户'));
        expect(updatedUserFromDb.email, equals('updated@example.com'));
        expect(updatedUserFromDb.department, equals('产品部'));
      });

      test('搜索用户测试', () async {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        // 先创建用户
        final user = User(
          username: 'searchuser_$timestamp',
          passwordHash: DatabaseHelper.hashPassword('testpass123'),
          realName: '搜索测试用户',
          email: 'search@example.com',
          phone: '13800138000',
          role: 1,
          department: '技术部',
          position: '开发工程师',
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final createSuccess = await userService.createUser(user);
        expect(createSuccess, isTrue);

        // 搜索用户名
        final usersByName = await userService.searchUsers('searchuser_$timestamp');
        expect(usersByName.length, greaterThan(0));
        expect(usersByName.first.username, equals('searchuser_$timestamp'));

        // 搜索真实姓名
        final usersByRealName = await userService.searchUsers('搜索测试用户');
        expect(usersByRealName.length, greaterThan(0));
        expect(usersByRealName.first.realName, equals('搜索测试用户'));

        // 搜索邮箱
        final usersByEmail = await userService.searchUsers('search@example.com');
        expect(usersByEmail.length, greaterThan(0));
        expect(usersByEmail.first.email, equals('search@example.com'));
      });

      test('切换用户状态测试', () async {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        // 先创建用户
        final user = User(
          username: 'toggleuser_$timestamp',
          passwordHash: DatabaseHelper.hashPassword('testpass123'),
          realName: '状态切换测试用户',
          email: 'toggle@example.com',
          phone: '13800138000',
          role: 1,
          department: '技术部',
          position: '开发工程师',
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final createSuccess = await userService.createUser(user);
        expect(createSuccess, isTrue);

        final createdUser = await userService.getUserByUsername('toggleuser_$timestamp');
        expect(createdUser, isNotNull);

        final originalStatus = createdUser!.isActive;
        final success = await userService.toggleUserStatus(createdUser.id!);
        expect(success, isTrue);

        // 验证状态是否切换
        final updatedUser = await userService.getUserById(createdUser.id!);
        expect(updatedUser, isNotNull);
        expect(updatedUser!.isActive, equals(!originalStatus));
      });

      test('删除用户测试', () async {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        // 先创建用户
        final user = User(
          username: 'deleteuser_$timestamp',
          passwordHash: DatabaseHelper.hashPassword('testpass123'),
          realName: '删除测试用户',
          email: 'delete@example.com',
          phone: '13800138000',
          role: 1,
          department: '技术部',
          position: '开发工程师',
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final createSuccess = await userService.createUser(user);
        expect(createSuccess, isTrue);

        final createdUser = await userService.getUserByUsername('deleteuser_$timestamp');
        expect(createdUser, isNotNull);

        final success = await userService.deleteUser(createdUser!.id!);
        expect(success, isTrue);

        // 验证用户是否被软删除
        final deletedUser = await userService.getUserById(createdUser.id!);
        expect(deletedUser, isNull); // 软删除后查询不到

        // 验证用户列表不包含已删除用户
        final allUsers = await userService.getAllUsers();
        final deletedUserInList = allUsers.where((u) => u.id == createdUser.id).toList();
        expect(deletedUserInList, isEmpty);
      });
    });

    group('用户统计测试', () {
      test('获取用户统计信息测试', () async {
        final stats = await userService.getUserStatistics();
        
        expect(stats, isNotNull);
        expect(stats.containsKey('total'), isTrue);
        expect(stats.containsKey('active'), isTrue);
        expect(stats.containsKey('admin'), isTrue);
        
        expect(stats['total'], isA<int>());
        expect(stats['active'], isA<int>());
        expect(stats['admin'], isA<int>());
        
        // 验证统计数据的合理性
        expect(stats['total']!, greaterThanOrEqualTo(0));
        expect(stats['active']!, greaterThanOrEqualTo(0));
        expect(stats['admin']!, greaterThanOrEqualTo(0));
        expect(stats['active']!, lessThanOrEqualTo(stats['total']!));
        expect(stats['admin']!, lessThanOrEqualTo(stats['total']!));
      });
    });

    group('用户数据验证测试', () {
      test('用户数据验证 - 有效数据', () {
        final validationResult = UserService.validateUserData(
          username: 'validuser',
          password: 'validpass123',
          realName: '有效用户',
          email: 'valid@example.com',
          phone: '13800138000',
          department: '技术部',
          position: '开发工程师',
        );

        expect(validationResult['username'], isNull);
        expect(validationResult['password'], isNull);
        expect(validationResult['realName'], isNull);
        expect(validationResult['email'], isNull);
        expect(validationResult['phone'], isNull);
        expect(validationResult['department'], isNull);
        expect(validationResult['position'], isNull);
      });

      test('用户数据验证 - 无效数据', () {
        final validationResult = UserService.validateUserData(
          username: 'ab', // 太短
          password: '123', // 太短
          realName: '', // 空
          email: 'invalid-email', // 无效邮箱
          phone: '123456789', // 不是11位
          department: 'a' * 101, // 超过100字符
          position: 'a' * 101, // 超过100字符
        );

        expect(validationResult['username'], isNotNull);
        expect(validationResult['password'], isNotNull);
        expect(validationResult['realName'], isNotNull);
        expect(validationResult['email'], isNotNull);
        expect(validationResult['phone'], isNotNull);
        expect(validationResult['department'], isNotNull);
        expect(validationResult['position'], isNotNull);
      });
    });

    group('边界条件测试', () {
      test('创建重复用户名测试', () async {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        final user1 = User(
          username: 'duplicateuser_$timestamp',
          passwordHash: DatabaseHelper.hashPassword('pass123'),
          realName: '重复用户1',
          role: 1,
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final user2 = User(
          username: 'duplicateuser_$timestamp', // 相同用户名
          passwordHash: DatabaseHelper.hashPassword('pass456'),
          realName: '重复用户2',
          role: 1,
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        // 第一个用户应该创建成功
        final success1 = await userService.createUser(user1);
        expect(success1, isTrue);

        // 第二个用户应该创建失败（用户名重复）
        final success2 = await userService.createUser(user2);
        expect(success2, isFalse);
      });

      test('删除不存在的用户测试', () async {
        final success = await userService.deleteUser(99999); // 不存在的ID
        expect(success, isFalse);
      });

      test('更新不存在的用户测试', () async {
        final nonExistentUser = User(
          id: 99999,
          username: 'nonexistent',
          passwordHash: DatabaseHelper.hashPassword('pass123'),
          realName: '不存在的用户',
          role: 1,
          isActive: true,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          isDeleted: false,
        );

        final success = await userService.updateUser(nonExistentUser);
        expect(success, isFalse);
      });

      test('搜索空关键词测试', () async {
        final users = await userService.searchUsers('');
        expect(users, isA<List<User>>());
        // 空关键词应该返回所有用户
        expect(users.length, greaterThanOrEqualTo(0));
      });
    });
  });
} 